package com.whz.workmanageol.security;

import com.whz.workmanageol.entity.User;
import com.whz.workmanageol.service.StudentService;
import com.whz.workmanageol.service.TeacherService;
import com.whz.workmanageol.vo.CourseVO;
import com.whz.workmanageol.vo.GradeCourseVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Component("customAuthenticationSuccessHandler")
public class CustomAuthenticationSuccessHandler
        extends SavedRequestAwareAuthenticationSuccessHandler {
    private static Logger logger = LoggerFactory.getLogger(CustomAuthenticationSuccessHandler.class);
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private StudentService studentService;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws ServletException, IOException {
        MyUserPrincipal userPrincipal = (MyUserPrincipal) authentication.getPrincipal();
        User user = userPrincipal.getUser();
        logger.info("sessionId: {}", request.getSession().getId());
        // 保存当前用户
        request.getSession().setAttribute("user", user);
        // 设置username 和 password 的cookie
        Cookie usernameCook = new Cookie("username", user.getUserid());
        Cookie passwordCook = new Cookie("password", user.getPassword());
        usernameCook.setMaxAge(60 * 60 * 24 * 7);
        passwordCook.setMaxAge(60 * 60 * 24 * 7);
        response.addCookie(usernameCook);
        response.addCookie(passwordCook);
        if("teacher".equals(user.getRole())){
            // 角色为教师 需要加载所授课程名称
            List<GradeCourseVO> gradeCourseVOS = teacherService.getGradeCourseByTea(user.getId());
            request.getSession().setAttribute("gradeCourseVOS", gradeCourseVOS);

        }
        if("student".equals(user.getRole())){
            // 角色为学生 需要加载课程名称
            List<CourseVO> courseVOList = studentService.findCoure(user.getId());
            request.getSession().setAttribute("courseVOList", courseVOList);
        }
        response.sendRedirect("/index");
    }
}
